<?php


namespace app\common\service;

class AppCardBuy
{
	public static function getOrderKey($order)
	{
		return sha1(md5($order["id"] . ($order["appid"] ?? 0) . $order["order_no"]));
	}
	public static function getCardBuyOrderArray($order, $hide_delivery_data = true)
	{
		return ["id" => $order["id"], "appid" => $order["appid"], "user" => $order["user"], "order_no" => $order["order_no"], "pay_type" => $order["pay_type"], "pay_status" => $order["pay_status"], "price" => $order["price"], "goods_type" => $order["goods_type"], "goods_value" => $order["goods_value"], "goods_num" => $order["goods_num"], "create_time" => $order["create_time"], "payment_time" => $order["payment_time"], "create_time_str" => date("Y-m-d H:i:s", $order["create_time"]), "payment_time_str" => $order["payment_time"] ? date("Y-m-d H:i:s", $order["payment_time"]) : "未付款", "delivery_data" => $order["query_password"] && $hide_delivery_data ? [] : json_decode($order["delivery_data"], true) ?? [], "is_verify_query_password" => $order["query_password"] && $hide_delivery_data];
	}
	public static function createCardBuyOrder($options, $app = [])
	{
		if (!$app) {
			$app = \think\Db::name("app")->where(["id" => $options["appid"]])->find();
			if (empty($app)) {
				return ["code" => Code::fail, "msg" => "应用ID不存在"];
			}
		}
		$isSystemAuthUnpaid = isSystemAuthUnpaid();
		if ($isSystemAuthUnpaid && \think\Db::name("app_order")->where(["appid" => $app["id"], "pay_status" => 1])->count() >= \app\common\model\FreeQuota::OrderAppPayQuota) {
			return ["code" => Code::fail, "msg" => "当前授权为基础版,一个应用付款订单数量上限为" . \app\common\model\FreeQuota::OrderAppPayQuota . \app\common\model\DefaultConfig::SystemAuthUnpaidSuffixText];
		}
		if ($isSystemAuthUnpaid && \think\Db::name("app_order")->where(["appid" => $app["id"]])->count() >= \app\common\model\FreeQuota::OrderAppQuota) {
			return ["code" => Code::fail, "msg" => "当前授权为基础版,一个应用订单数量上限为" . \app\common\model\FreeQuota::OrderAppQuota . \app\common\model\DefaultConfig::SystemAuthUnpaidSuffixText];
		}
		$buy_config = json_decode($app["buy_config"], true);
		if (!empty($buy_config["common_buy_card"]["close_buy_card"])) {
			return ["code" => 10023, "msg" => "未开启功能"];
		}
		if (!empty($buy_config["common_buy_card"]["query_password_must"]) && empty($options["password"])) {
			return ["code" => 10024, "msg" => "未设置取卡密码"];
		}
		if (empty($buy_config["common_buy_card"]["price"][$options["type"]])) {
			return ["code" => 10025, "msg" => "未配置购买价格"];
		}
		if ($options["type"] != \app\common\model\CardTimeType::Perpetual[0]) {
			$price = $buy_config["common_buy_card"]["price"][$options["type"]] * $options["value"] * $options["num"];
		} else {
			$price = $buy_config["common_buy_card"]["price"][$options["type"]] * 1 * $options["num"];
		}
		if ($price < 0.01) {
			return ["code" => 10026, "msg" => "订单总价不能小于0.01元"];
		}
		$card_type = $options["type"];
		$time_value = $options["value"];
		$num = $options["num"];
		$add_card_minimum_face_value_config = $buy_config["common_buy_card"]["add_card_minimum_face_value_config"][$card_type] ?? 0;
		if (!empty($add_card_minimum_face_value_config) && $time_value < $add_card_minimum_face_value_config) {
			return ["code" => 10027, "msg" => "下单失败,根据购卡规则面值/时长不能低于" . $add_card_minimum_face_value_config];
		}
		$add_card_maximum_face_value_config = $buy_config["common_buy_card"]["add_card_maximum_face_value_config"][$card_type] ?? 0;
		if (!empty($add_card_maximum_face_value_config) && $add_card_maximum_face_value_config < $time_value) {
			return ["code" => 10028, "msg" => "下单失败,根据购卡规则面值/时长不能高于" . $add_card_maximum_face_value_config];
		}
		$add_card_minimum_quantity_config = $buy_config["common_buy_card"]["add_card_minimum_quantity_config"][$card_type] ?? 0;
		if (!empty($add_card_minimum_quantity_config) && $num < $add_card_minimum_quantity_config) {
			return ["code" => 10029, "msg" => "下单失败,根据购卡规则下单数量不能低于" . $add_card_minimum_quantity_config];
		}
		$add_card_maximum_quantity_config = $buy_config["common_buy_card"]["add_card_maximum_quantity_config"][$card_type] ?? 0;
		if (!empty($add_card_maximum_quantity_config) && $add_card_maximum_quantity_config < $num) {
			return ["code" => 10030, "msg" => "下单失败,根据购卡规则下单数量不能高于" . $add_card_maximum_quantity_config];
		}
		$order_no = create_order_no();
		if ($app["type"] == 0) {
			$type = \app\common\model\BuyType::CardAppBuyCard;
		} elseif ($app["type"] == 1) {
			$type = \app\common\model\BuyType::MemberAppBuyCard;
		} elseif ($app["type"] == 2) {
			$type = \app\common\model\BuyType::AuthAppBuyCard;
		} else {
			return ["code" => 10031, "msg" => "不存在的卡密类型"];
		}
		$order = ["appid" => $app["id"], "order_no" => $order_no, "type" => $type, "goods_type" => $options["type"], "goods_num" => $options["num"], "goods_value" => $options["value"], "pay_type" => $options["pay_type"], "user" => $options["phone"], "query_password" => $options["password"] ?? "", "create_time" => time(), "price" => $price];
		$order_id = \think\Db::name("app_order")->insertGetId($order);
		$order["id"] = $order_id;
		$order["order_key"] = self::getOrderKey($order);
		return ["code" => Code::success, "msg" => "下单成功", "data" => $order];
	}
	public static function queryCardBuyOrder($options, $app = [])
	{
		if (!$app) {
			$app = \think\Db::name("app")->where(["id" => $options["appid"]])->find();
			if (empty($app)) {
				return ["code" => Code::fail, "msg" => "应用ID不存在"];
			}
		}
		if ($app["type"] == 0) {
			$type = \app\common\model\BuyType::CardAppBuyCard;
		} elseif ($app["type"] == 1) {
			$type = \app\common\model\BuyType::MemberAppBuyCard;
		} elseif ($app["type"] == 2) {
			$type = \app\common\model\BuyType::AuthAppBuyCard;
		} else {
			return ["code" => 10032, "msg" => "不存在的卡密类型"];
		}
		$minimum_time = strtotime(date("Y-m-d H:i:s") . " -30 day");
		if ($options["type"] == 1) {
			$order_list = \think\Db::name("app_order")->where([["", "exp", \think\Db::raw("order_no='{$options["value"]}' or supplier_no='{$options["value"]}'")], ["create_time", ">=", $minimum_time], ["type", "=", $type], ["appid", "=", $app["id"]]])->order("id", "desc")->limit(50)->select();
		} elseif ($options["type"] == 2) {
			$order_list = \think\Db::name("app_order")->where([["user", "=", $options["value"]], ["create_time", ">=", $minimum_time], ["type", "=", $type], ["appid", "=", $app["id"]]])->order("id", "desc")->limit(50)->select();
		} else {
			return ["code" => 10033, "msg" => "不支持的查询方式"];
		}
		$data = [];
		foreach ($order_list as $order) {
			$data[] = AppCardBuy::getCardBuyOrderArray($order, \boolval($order["query_password"]));
		}
		return ["code" => Code::success, "msg" => "查询成功", "data" => $data];
	}
	public static function getOrderInfo($options, $app = [])
	{
		$order = \think\Db::name("app_order")->where(["id" => $options["order_id"]])->find();
		if (empty($order)) {
			return ["code" => 10034, "msg" => "订单id不存在"];
		}
		if ($options["order_key"] != self::getOrderKey($order)) {
			return ["code" => 10035, "msg" => "order_key 错误"];
		}
		$data = self::getCardBuyOrderArray($order);
		return ["code" => Code::success, "msg" => "查询成功", "data" => $data];
	}
	public static function queryCardBuyOrderDeliveryData($options, $app = [])
	{
		$order = \think\Db::name("app_order")->where(["order_no" => $options["order_no"]])->find();
		if (empty($order)) {
			return ["code" => 10036, "msg" => "订单不存在"];
		}
		if ($order["pay_status"] == 0) {
			return ["code" => 10037, "msg" => "订单未付款"];
		}
		if ($order["query_password"] == "" || $order["query_password"] != $options["password"]) {
			return ["code" => 10038, "msg" => "查询密码错误"];
		}
		return ["code" => Code::success, "msg" => "查询成功", "data" => json_decode($order["delivery_data"], true) ?? []];
	}
	public static function createRenewalOrder($options, $app = [])
	{
		if (!$app) {
			$app = \think\Db::name("app")->where(["id" => $options["appid"]])->find();
			if (empty($app)) {
				return ["code" => Code::fail, "msg" => "应用ID不存在"];
			}
		}
		$isSystemAuthUnpaid = isSystemAuthUnpaid();
		if ($isSystemAuthUnpaid) {
			return ["code" => Code::fail, "msg" => "当前授权为基础版,不支持卡密续费功能" . \app\common\model\DefaultConfig::SystemAuthUnpaidSuffixText];
		}
		if ($isSystemAuthUnpaid && \think\Db::name("app_order")->where(["appid" => $app["id"], "pay_status" => 1])->count() >= \app\common\model\FreeQuota::OrderAppPayQuota) {
			return ["code" => Code::fail, "msg" => "当前授权为基础版,一个应用付款订单数量上限为" . \app\common\model\FreeQuota::OrderAppPayQuota . \app\common\model\DefaultConfig::SystemAuthUnpaidSuffixText];
		}
		if ($isSystemAuthUnpaid && \think\Db::name("app_order")->where(["appid" => $app["id"]])->count() >= \app\common\model\FreeQuota::OrderAppQuota) {
			return ["code" => Code::fail, "msg" => "当前授权为基础版,一个应用订单数量上限为" . \app\common\model\FreeQuota::OrderAppQuota . \app\common\model\DefaultConfig::SystemAuthUnpaidSuffixText];
		}
		$buy_config = json_decode($app["buy_config"], true);
		if (!empty($buy_config["common_buy_renewal"]["close_renewal"])) {
			return ["code" => 10147, "msg" => "未开启功能"];
		}
		if (empty($buy_config["common_buy_renewal"]["price"][$options["type"]])) {
			return ["code" => 10148, "msg" => "下单失败,未配置价格"];
		}
		if ($options["type"] != \app\common\model\CardTimeType::Perpetual[0]) {
			$price = $buy_config["common_buy_renewal"]["price"][$options["type"]] * $options["value"];
		} else {
			$price = $buy_config["common_buy_renewal"]["price"][$options["type"]];
		}
		if ($price < 0.01) {
			return ["code" => 10149, "msg" => "订单总价不能小于0.01元"];
		}
		if ($app["type"] === 0) {
			$type = \app\common\model\BuyType::CardAppUserRenewal;
			$card = \think\Db::name("app_card_user")->where(["appid" => $app["id"], "card" => $options["user"]])->find();
			if (empty($card)) {
				return ["code" => 10150, "msg" => "卡密不存在"];
			}
			if ($card["status"] == 0) {
				return ["code" => 10151, "msg" => "卡密未使用不支持充值续费"];
			}
			$user_id = $card["id"];
		} elseif ($app["type"] === 1) {
			$type = \app\common\model\BuyType::MemberAppUserRenewal;
			$field = "account";
			if (!empty($options["use_user_id"])) {
				$field = "id";
			}
			$user = \think\Db::name("app_member_user")->where(["appid" => $app["id"], $field => $options["user"]])->find();
			if (empty($user)) {
				return ["code" => 10152, "msg" => "用户不存在"];
			}
			$user_id = $user["id"];
		} elseif ($app["type"] === 2) {
			$type = \app\common\model\BuyType::AuthAppUserRenewal;
			$user = \think\Db::name("app_auth_user")->where(["appid" => $app["id"], "auth" => $options["user"]])->find();
			if (empty($options["auth_type"]) || $options["auth_type"] === "renewal_auth" || !is_numeric($options["value"])) {
				if (empty($user)) {
					return ["code" => 10153, "msg" => "授权用户不存在"];
				}
				$user_id = $user["id"];
			} else {
				if ($options["auth_type"] === "new_auth") {
					$user_id = $options["user"];
				}
			}
		}
		$card_type = $options["type"];
		$time_value = $options["value"];
		$add_card_minimum_face_value_config = $buy_config["common_buy_renewal"]["add_card_minimum_face_value_config"][$card_type] ?? 0;
		if (!empty($add_card_minimum_face_value_config) && $time_value < $add_card_minimum_face_value_config) {
			return ["code" => 10154, "msg" => "下单失败,根据交易规则面值/时长不能低于" . $add_card_minimum_face_value_config];
		}
		$add_card_maximum_face_value_config = $buy_config["common_buy_renewal"]["add_card_maximum_face_value_config"][$card_type] ?? 0;
		if (!empty($add_card_maximum_face_value_config) && $add_card_maximum_face_value_config < $time_value) {
			return ["code" => 10155, "msg" => "下单失败,根据交易规则面值/时长不能高于" . $add_card_maximum_face_value_config];
		}
		$order_no = create_order_no();
		$order = ["appid" => $app["id"], "order_no" => $order_no, "type" => $type, "goods_type" => $options["type"], "goods_num" => 1, "goods_value" => $options["value"], "pay_type" => $options["pay_type"], "user" => $user_id, "create_time" => time(), "price" => $price];
		$order_id = \think\Db::name("app_order")->insertGetId($order);
		$order["id"] = $order_id;
		$order["order_key"] = AppCardBuy::getOrderKey($order);
		return ["code" => Code::success, "msg" => "创建订单成功", "data" => $order];
	}
}